// components/permissions/permissions.js
const app = getApp()
Component({

  /**
   * 页面的初始数据
   */
  data: {
    actions:[],
    actionSheetShow: false,
    userInfo:app.globalData.userInfo,
    avatarUrl: app.globalData.avatarUrl,
    nickName: app.globalData.nickName,
    popup: false,
    phoneNum: app.globalData.phoneNum,
    code: '',
    accessToken: '',
    token: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
   attached: function (options) {
    let that = this
    // 是否显示获取用户头像昵称弹窗
        // 登录
        wx.login({
          success: res => {
            that.setData({
              code: res.code
            })
            that.isUserExit(res.code)
          },
          fail: errr => {
            console.log(errr)
          }
        })
    app.watchUserInfo(that.watchBackUserInfo)
    app.watchPhoneNum(that.watchBackPhoneNum)
    app.watchAvatarUrl(that.watchBackavatarUrl)
    app.watchNickName(that.watchBackNickName)
  },
  methods: {

  // 判断用户是否存在
  isUserExit(code) {
    let that = this
    wx.request({
      url: `${app.globalData.baseUrl}/api/wechat/checkUser`,
      method: 'POST',
      data: {
        code: code
      },
      success: function (res) {
        // 用户没有登录过小程序
        if(!res.data.result) {
          that.getWxToken() 
          that.setData({
            actionSheetShow: true
          })
        } else {
        // 用户登录过小程序
        that.setData({
          actionSheetShow: false
        })
          wx.setStorageSync('token', res.data.result.token) 
          app.globalData.phoneNum = res.data.result.phoneNumber
          app.globalData.avatarUrl = res.data.result.avatarUrl
          app.globalData.nickName = res.data.result.wxName
        }
      }
    })
  },

  // 获取用户头像 昵称
  getUserProfile(e) {
    let that = this
    // that.getWxToken()  // 获取微信token
    // that.setData({
    //   actionSheetShow: false
    // })
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        app.globalData.hasUserInfo = true
        app.globalData.userInfo = res.userInfo
        app.globalData.avatarUrl = res.userInfo.avatarUrl
        app.globalData.nickName = res.userInfo.nickName
        that.setData({
          iv: res.iv,
          encryptedData: res.encryptedData,
          popup: true,
          actionSheetShow: false
        })
      },
      fail: (err) => {
        that.setData({
          actionSheetShow: true
        })
      }
    })
  },

  // 获取微信token
  getWxToken: function() {
    let that = this
    let url = `${app.globalData.baseUrl}/api/wechat/getWxToken`
    wx.request({
      url: url,
      method: 'GET',
      success: (res) => {
        if(res.data.code === 200) {
          that.setData({
            accessToken: res.data.result.accessToken
          })
        }
      },
      fail: (error) => {
        console.log(error)
      }
    })
  },
  // 获取手机号码
  getPhoneNumber: function(e) {
    let that = this
    let ACCESS_TOKEN = that.data.accessToken
    let code = e.detail.code
    console.log(that.data.accessToken,'ACCESS_TOKEN',e.detail.code)
    that.setData({
      popup: false
    })
    // let url = `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${ACCESS_TOKEN}`
    let url = `${app.globalData.baseUrl}/api/wechat/phonenumber`
    wx.request({
      url: url,
      method: 'POST',
      data: {
        code: code,
        accessToken: ACCESS_TOKEN
      },
      success: function(res) {
        console.log(res,'haha')
        if(res.data.code === 200) {
          let phoneNum = res.data.result.slice(0,3) + "****" + res.data.result.slice(7,11)
          app.globalData.phoneNum = phoneNum
          console.log(app.globalData.phoneNum, 'app.globalData.phoneNum123')
          // 调用登录接口
          that.login(res.data.result)
        } else {
          wx.showToast({
            title: '失败',
            icon: 'error',
            duration: 2000
          })
        }
      },
      fail: (err) => {
        that.setData({
          popup: false
        })
      }
    })
  },

  // 登录接口调用
  login(phoneNumber) {
    let that = this
    let url = `${app.globalData.baseUrl}/api/login`
    wx.showLoading({
      title: '加载中',
    })
    setTimeout(function () {
      wx.hideLoading()
    }, 3000)
    wx.login({
      success: res => {
        wx.request({
          url: url,
          method: 'POST',
          data: {
            code: res.code,
            // rawData: infoRes.rawData,
            // signature:infoRes.signature,//签名
            encryptedData:that.data.encryptedData,//用户敏感信息
            iv:that.data.iv,//解密算法的向量
            phoneNumber: phoneNumber
          },
          success: function(result) {
            if(result.data.code === 0) {
              that.data.token = result.data.token
              wx.showToast({
                title: '授权成功',
                icon: 'success',
                duration: 3000
              })
              if(result.data.token) {
                wx.setStorageSync('token', result.data.token) 
              }
            }
          },
          fail: function(err) {
            wx.showToast({
              title: '授权失败，请联系区慧勤务中心',
              icon: 'error',
              duration: 2000
            })
          }
        })
      },
      fail: errr => {
        console.log(errr)
      }
    })

  },

  watchBackUserInfo(userInfo) {
    console.log('监听到的数据userInfo：' + userInfo)
    let that = this
    that.setData({
      userInfo: userInfo
    })
  },
  watchBackPhoneNum(phoneNum) {
    console.log('监听到的数据phoneNum：' + phoneNum)
    let that = this
    that.setData({
      phoneNum: phoneNum
    })
  },
},

//  watchBack(actionSheetShow){
//     console.log('监听到的数据actionSheetShow：' + actionSheetShow)
//     let that = this
//     that.setData({
//       actionSheetShow: actionSheetShow
//     })
//   },
//   watchBackPopup(popup) {
//     console.log('监听到的数据popup：' + popup)
//     let that = this
//     that.setData({
//       popup: popup
//     })
//   },
//   watchBackUserInfo(userInfo) {
//     console.log('监听到的数据userInfo：' + userInfo)
//     let that = this
//     that.setData({
//       userInfo: userInfo
//     })
//   },
//   watchBackPhoneNum(phoneNum) {
//     console.log('监听到的数据phoneNum：' + phoneNum)
//     let that = this
//     that.setData({
//       phoneNum: phoneNum
//     })
//   },
//   getUserProfiles(e) {
//     getApp().getUserProfile(e)
//   },
//   getPhoneNumber(e) {
//     let getPhoneCode = e.detail.code
//     getApp().getPhoneNumbers(getPhoneCode)
//   },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})